package com.dc.base.view.recyclerview

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

abstract class CommonRecyclerAdapter<T>(
    val context: Context,
    var dataList: MutableList<T>,
    var layoutId: Int
) :
    RecyclerView.Adapter<ViewHolder>() {

    private var mTypeSupport: MulitiTypeSupport<T>? = null

    var mItemClick: ((Int, T) -> Unit)? = null
    var mItemLongClick: ((Int, T) -> Boolean)? = null

    constructor(context: Context, datas: MutableList<T>, typeSupport: MulitiTypeSupport<T>?) : this(
        context,
        datas,
        -1
    ) {
        mTypeSupport = typeSupport
    }


    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        mTypeSupport?.let {
            layoutId = viewType
        }
        val itemView = LayoutInflater.from(context).inflate(layoutId, parent, false)
        return ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        dataList[position].run {
            convert(holder, this, position)
            holder.itemView.setOnClickListener {
                mItemClick?.invoke(position, this)
            }
            holder.itemView.setOnLongClickListener {
                mItemLongClick?.invoke(position, this) ?: false
            }
        }
    }

    abstract fun convert(holder: ViewHolder, t: T, position: Int)

    public fun setData(dataList: List<T>) {
        if (dataList.isEmpty()) {
            return
        }
        this.dataList.clear()
        this.dataList.addAll(dataList)
        notifyDataSetChanged()
    }

    fun addData(dataList: List<T>) {
        if (dataList.isEmpty()) {
            return
        }
        this.dataList.addAll(dataList)
        notifyItemRangeInserted(this.dataList.size, dataList.size)
    }

    override fun getItemViewType(position: Int): Int {
        return mTypeSupport?.getLayoutId(dataList[position]) ?: super.getItemViewType(position)
    }
}